import React, { memo, useCallback, useRef } from 'react';
import { FormHeader, Icon } from '@/pages/Recruitment/components';
import { message, Popconfirm, Spin, Tag } from 'antd';
import { TEMPLATE_TYPE } from '@/pages/Recruitment/Setting/constants';
import { DividerContainer } from '@/molecules';
import { history } from 'umi'
import { useRequest } from '@/hooks';
import { deleteNoticeTemplate, getNoticeTemplateList } from '@/pages/Recruitment/Setting/service';
import authHelper from '@/utils/auth/helper';
import LinkTo from '@/components/LinkTo';
import TemplatePreview from '../TemplatePreview';
import TemplateTable from '../TemplateTable';

const { checkCode } = authHelper;


const EmployedInfoTemplate = props => {
    const previewRef = useRef();
    // 获取模板列表
    const { data: templateData, loading: templateLoading, run: fetchTemplateList } = useRequest(
        () => getNoticeTemplateList({ templateCategory: 2, pageSize: 99999 }),
        {
            manual: true,
            initialData: { interviewList: [] },
            formatResult: result => {
                const { code, data, msg } = result;
                if (code === 10000) {
                    const { rows = [] } = data;
                    return {
                        offerInfoList: rows.filter(item => item.templateType === TEMPLATE_TYPE.OFFER_INFO)
                    };
                }
                message.error(msg);
                return { offerInfoList: [] };
            }
        }
    );

    // 删除模板
    const { run: delNoticeTemplate } = useRequest(deleteNoticeTemplate, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchTemplateList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    const handleDelete = id => {
        if (id) {
            delNoticeTemplate(id);
        }
    };

    const handleViewDetail = record => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/setting/employed/detail',
            query: { id: record.id, type: record.templateType },
            state: { tabRoute: true, tabRefresh: true }
        });
    };

    const handlePreview = useCallback(record => {
        previewRef.current.open(record.id);
    }, []);

    React.useEffect(() => {
        fetchTemplateList();
    }, []);
    const columns = [
        {
            title: '模板名称',
            dataIndex: 'templateName',
            ellipsis: true,
            render: (text, record) => {
                const { isDefault } = record;
                return <div style={{ display: 'flex', alignItems: 'center' }}>
                    <LinkTo isDefault onClick={() => { handleViewDetail(record) }}>
                        {text}
                    </LinkTo>
                    {isDefault === 1 && <Tag color="orange" style={{ marginLeft: 8 }}>默认</Tag>}
                </div>
            }
        },
        {
            title: '适用行政机构',
            dataIndex: 'organizationNames',
            ellipsis: true,
            width: '40%',
            render: (text, record) => (record.isDefault === 1 ? '全集团' : text.replace(/,/g, '、'))
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 130,
            fixed: 'right',
            render: (text, record) => (
                <DividerContainer>
                    <Icon
                        isAntdIcon
                        size={14}
                        title="预览"
                        type="eye"
                        onClick={() => {
                            handlePreview(record)
                        }}
                    />
                    {checkCode('office:recruitment:setting:employed:update') && (
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/setting/notice/employInfoEdit',
                                    query: { id: record.id, type: record.templateType },
                                    state: { tabRoute: true, tabRefresh: true }
                                });
                            }}
                        />
                    )}
                    {checkCode('office:recruitment:setting:employed:delete') && !record.isDefault && (
                        <Popconfirm
                            title="你确定要删除这行内容吗？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => handleDelete(record.id)}
                        >
                            <Icon title="删除" type="listfunction_delete_icon_default" />
                        </Popconfirm>
                    )}
                </DividerContainer>
            )
        }
    ];

    const titleStyle = { color: 'rgba(0, 0, 0, 0.3)' };
    return <div style={{ marginBottom: 24 }} { ...props }>
        <FormHeader title="录用信息模板" style={{ marginBottom: 8 }} />
        <div style={{ ...titleStyle, marginBottom: 12 }}>配置录用通知邮件中的录用信息</div>
        <Spin spinning={templateLoading}>
            <TemplateTable
                rowKey="id"
                columns={columns}
                dataSource={templateData?.offerInfoList}
                loading={templateLoading}
                pagination={false}
                authCode="office:recruitment:setting:employed:create"
                type={TEMPLATE_TYPE.OFFER_INFO}
            />
        </Spin>
        <TemplatePreview ref={previewRef} type={TEMPLATE_TYPE.OFFER_INFO}/>
    </div>
}
export default memo(EmployedInfoTemplate)
